<template>
  <div class="system-config-container">
    <el-card class="system-config-header">
      <template #header>
        <div class="card-header">
          <span>系统参数配置</span>
          <el-button type="primary" size="small" @click="refreshCache">刷新缓存</el-button>
        </div>
      </template>
      <div class="config-summary">
        <div class="summary-item">
          <div class="summary-icon">
            <i class="el-icon-setting"></i>
          </div>
          <div class="summary-content">
            <div class="summary-title">系统参数</div>
            <div class="summary-value">{{ statistics.configCount }}</div>
          </div>
        </div>
        <div class="summary-item">
          <div class="summary-icon">
            <i class="el-icon-paperclip"></i>
          </div>
          <div class="summary-content">
            <div class="summary-title">缓存键数</div>
            <div class="summary-value">{{ statistics.cacheKeyCount }}</div>
          </div>
        </div>
        <div class="summary-item">
          <div class="summary-icon">
            <i class="el-icon-finished"></i>
          </div>
          <div class="summary-content">
            <div class="summary-title">修改日志</div>
            <div class="summary-value">{{ statistics.logCount }}</div>
          </div>
        </div>
      </div>
    </el-card>
    
    <el-tabs v-model="activeTab" type="card" class="config-tabs">
      <el-tab-pane label="系统参数" name="params">
        <el-card class="config-card">
          <template #header>
            <div class="card-header">
              <span>系统参数列表</span>
              <div>
                <el-button type="primary" size="small" @click="handleAddConfig">
                  <i class="el-icon-plus"></i> 新增参数
                </el-button>
              </div>
            </div>
          </template>
          
          <!-- 搜索表单 -->
          <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
            <el-form-item label="参数名称" prop="configName">
              <el-input
                v-model="queryParams.configName"
                placeholder="请输入参数名称"
                clearable
              />
            </el-form-item>
            <el-form-item label="参数键名" prop="configKey">
              <el-input
                v-model="queryParams.configKey"
                placeholder="请输入参数键名"
                clearable
              />
            </el-form-item>
            <el-form-item label="系统内置" prop="configType">
              <el-select v-model="queryParams.configType" placeholder="请选择" clearable>
                <el-option label="是" value="Y" />
                <el-option label="否" value="N" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <i class="el-icon-search"></i> 搜索
              </el-button>
              <el-button @click="resetQuery">
                <i class="el-icon-refresh"></i> 重置
              </el-button>
            </el-form-item>
          </el-form>
          
          <!-- 系统参数表格 -->
          <el-table
            v-loading="loading"
            :data="configList"
            row-key="configId"
          >
            <el-table-column label="序号" type="index" width="50" align="center" />
            <el-table-column label="参数名称" prop="configName" :show-overflow-tooltip="true" />
            <el-table-column label="参数键名" prop="configKey" :show-overflow-tooltip="true" />
            <el-table-column label="参数值" prop="configValue" :show-overflow-tooltip="true" />
            <el-table-column label="系统内置" align="center" prop="configType">
              <template #default="scope">
                <el-tag type="success" v-if="scope.row.configType === 'Y'">是</el-tag>
                <el-tag type="info" v-else>否</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark" :show-overflow-tooltip="true" />
            <el-table-column label="操作" align="center" width="160">
              <template #default="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="handleUpdate(scope.row)"
                  v-if="scope.row.configType === 'N'"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  @click="handleDelete(scope.row)"
                  v-if="scope.row.configType === 'N'"
                >删除</el-button>
                <el-button
                  size="mini"
                  type="text"
                  @click="handleView(scope.row)"
                >详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              v-model:current-page="queryParams.pageNum"
              v-model:page-size="queryParams.pageSize"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane label="缓存管理" name="cache">
        <el-card class="config-card">
          <template #header>
            <div class="card-header">
              <span>缓存监控</span>
              <div>
                <el-button type="danger" size="small" @click="clearCache">
                  <i class="el-icon-delete"></i> 清空缓存
                </el-button>
              </div>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="cache-box">
                <div class="cache-title">缓存类型</div>
                <div class="cache-value">Redis</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="cache-box">
                <div class="cache-title">缓存键数量</div>
                <div class="cache-value">{{ cacheInfo.keyCount }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="cache-box">
                <div class="cache-title">缓存内存</div>
                <div class="cache-value">{{ cacheInfo.memorySize }}</div>
              </div>
            </el-col>
          </el-row>
          
          <!-- 缓存列表 -->
          <el-table
            v-loading="cacheLoading"
            :data="cacheList"
            style="margin-top: 20px"
          >
            <el-table-column label="序号" type="index" width="50" align="center" />
            <el-table-column label="缓存键名" prop="cacheKey" :show-overflow-tooltip="true" />
            <el-table-column label="缓存类型" prop="cacheType" width="120" />
            <el-table-column label="过期时间" prop="expireTime" width="180" />
            <el-table-column label="操作" align="center" width="160">
              <template #default="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="viewCache(scope.row)"
                >查看</el-button>
                <el-button
                  size="mini"
                  type="text"
                  @click="deleteCache(scope.row.cacheKey)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 添加或修改系统参数对话框 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="500px"
    >
      <el-form
        ref="configFormRef"
        :model="configForm"
        :rules="configRules"
        label-width="100px"
      >
        <el-form-item label="参数名称" prop="configName">
          <el-input v-model="configForm.configName" placeholder="请输入参数名称" />
        </el-form-item>
        <el-form-item label="参数键名" prop="configKey">
          <el-input 
            v-model="configForm.configKey" 
            placeholder="请输入参数键名"
            :disabled="dialog.type === 'update'" 
          />
        </el-form-item>
        <el-form-item label="参数值" prop="configValue">
          <el-input 
            v-model="configForm.configValue" 
            placeholder="请输入参数值" 
            type="textarea" 
            :rows="4"
          />
        </el-form-item>
        <el-form-item label="系统内置" prop="configType">
          <el-radio-group v-model="configForm.configType">
            <el-radio label="Y">是</el-radio>
            <el-radio label="N">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="configForm.remark" 
            placeholder="请输入备注"
            type="textarea"
            :rows="2" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 查看缓存内容对话框 -->
    <el-dialog
      title="缓存内容详情"
      v-model="cacheDialog.visible"
      width="700px"
    >
      <div class="cache-content-box">
        <pre>{{ cacheDialog.content }}</pre>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 控制标签页
const activeTab = ref('params')

// 是否显示搜索表单
const showSearch = ref(true)

// 统计数据
const statistics = reactive({
  configCount: 32,
  cacheKeyCount: 156,
  logCount: 487
})

// 加载状态
const loading = ref(false)
const cacheLoading = ref(false)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  configName: undefined,
  configKey: undefined,
  configType: undefined
})

// 总条数
const total = ref(0)

// 系统参数表格数据
const configList = ref([])

// 缓存信息
const cacheInfo = reactive({
  keyCount: 156,
  memorySize: '28.5 MB'
})

// 缓存列表
const cacheList = ref([])

// 对话框
const dialog = reactive({
  visible: false,
  title: '',
  type: '' // add/update
})

// 缓存对话框
const cacheDialog = reactive({
  visible: false,
  content: ''
})

// 配置表单
const configFormRef = ref(null)
const configForm = reactive({
  configId: undefined,
  configName: undefined,
  configKey: undefined,
  configValue: undefined,
  configType: 'N',
  remark: undefined
})

// 表单验证规则
const configRules = {
  configName: [
    { required: true, message: '参数名称不能为空', trigger: 'blur' }
  ],
  configKey: [
    { required: true, message: '参数键名不能为空', trigger: 'blur' }
  ],
  configValue: [
    { required: true, message: '参数值不能为空', trigger: 'blur' }
  ]
}

// 模拟数据 - 系统参数列表
const mockConfigs = [
  {
    configId: 1,
    configName: '系统名称',
    configKey: 'sys.name',
    configValue: '通用后台管理系统',
    configType: 'Y',
    remark: '系统名称显示在登录页和主页'
  },
  {
    configId: 2,
    configName: '系统版本',
    configKey: 'sys.version',
    configValue: 'v1.0.0',
    configType: 'Y',
    remark: '当前系统版本号'
  },
  {
    configId: 3,
    configName: '系统开发者',
    configKey: 'sys.author',
    configValue: 'NexusHub开发团队',
    configType: 'Y',
    remark: '系统开发者信息'
  },
  {
    configId: 4,
    configName: '账号初始密码',
    configKey: 'sys.user.initPassword',
    configValue: '123456',
    configType: 'N',
    remark: '用户初始密码'
  },
  {
    configId: 5,
    configName: '主页路径',
    configKey: 'sys.indexPage',
    configValue: '/dashboard',
    configType: 'Y',
    remark: '系统默认打开的首页'
  }
]

// 模拟数据 - 缓存列表
const mockCaches = [
  {
    cacheKey: 'sys:config:cache',
    cacheType: '系统配置',
    expireTime: '永不过期',
    cacheValue: JSON.stringify(mockConfigs)
  },
  {
    cacheKey: 'sys:user:cache',
    cacheType: '用户信息',
    expireTime: '2023-06-01 12:00:00',
    cacheValue: JSON.stringify([
      { id: 1, username: 'admin', name: '管理员' },
      { id: 2, username: 'test', name: '测试用户' }
    ])
  },
  {
    cacheKey: 'sys:menu:cache',
    cacheType: '菜单缓存',
    expireTime: '永不过期',
    cacheValue: JSON.stringify([
      { id: 1, name: '系统管理', path: '/system' },
      { id: 2, name: '用户管理', path: '/system/user' }
    ])
  },
  {
    cacheKey: 'sys:dict:cache',
    cacheType: '字典缓存',
    expireTime: '永不过期',
    cacheValue: JSON.stringify({
      status: [
        { value: '0', label: '正常' },
        { value: '1', label: '停用' }
      ],
      sex: [
        { value: '0', label: '男' },
        { value: '1', label: '女' },
        { value: '2', label: '未知' }
      ]
    })
  }
]

// 获取系统参数列表
const getConfigList = () => {
  loading.value = true
  // 模拟 API 请求
  setTimeout(() => {
    configList.value = mockConfigs
    total.value = mockConfigs.length
    loading.value = false
  }, 500)
}

// 获取缓存列表
const getCacheList = () => {
  cacheLoading.value = true
  // 模拟 API 请求
  setTimeout(() => {
    cacheList.value = mockCaches
    cacheLoading.value = false
  }, 500)
}

// 搜索参数
const handleQuery = () => {
  queryParams.pageNum = 1
  getConfigList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.configName = undefined
  queryParams.configKey = undefined
  queryParams.configType = undefined
  handleQuery()
}

// 分页每页条数变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getConfigList()
}

// 分页页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getConfigList()
}

// 添加系统参数
const handleAddConfig = () => {
  dialog.visible = true
  dialog.title = '添加系统参数'
  dialog.type = 'add'
  // 重置表单
  if (configFormRef.value) {
    configFormRef.value.resetFields()
  }
  configForm.configId = undefined
  configForm.configName = undefined
  configForm.configKey = undefined
  configForm.configValue = undefined
  configForm.configType = 'N'
  configForm.remark = undefined
}

// 修改系统参数
const handleUpdate = (row) => {
  dialog.visible = true
  dialog.title = '修改系统参数'
  dialog.type = 'update'
  // 重置表单
  if (configFormRef.value) {
    configFormRef.value.resetFields()
  }
  // 填充表单
  configForm.configId = row.configId
  configForm.configName = row.configName
  configForm.configKey = row.configKey
  configForm.configValue = row.configValue
  configForm.configType = row.configType
  configForm.remark = row.remark
}

// 查看系统参数
const handleView = (row) => {
  dialog.visible = true
  dialog.title = '查看系统参数'
  dialog.type = 'view'
  // 填充表单
  configForm.configId = row.configId
  configForm.configName = row.configName
  configForm.configKey = row.configKey
  configForm.configValue = row.configValue
  configForm.configType = row.configType
  configForm.remark = row.remark
}

// 删除系统参数
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除参数"${row.configName}"吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟 API 请求
    configList.value = configList.value.filter(item => item.configId !== row.configId)
    total.value = configList.value.length
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  configFormRef.value.validate((valid) => {
    if (valid) {
      if (dialog.type === 'add') {
        // 模拟添加
        const newConfig = {
          configId: Date.now(),
          configName: configForm.configName,
          configKey: configForm.configKey,
          configValue: configForm.configValue,
          configType: configForm.configType,
          remark: configForm.remark
        }
        configList.value.push(newConfig)
        total.value = configList.value.length
        ElMessage.success('添加成功')
      } else if (dialog.type === 'update') {
        // 模拟修改
        const index = configList.value.findIndex(item => item.configId === configForm.configId)
        if (index !== -1) {
          configList.value[index] = { ...configList.value[index], ...configForm }
          ElMessage.success('修改成功')
        }
      }
      dialog.visible = false
    }
  })
}

// 刷新缓存
const refreshCache = () => {
  ElMessage.success('缓存刷新成功')
}

// 清空缓存
const clearCache = () => {
  ElMessageBox.confirm('确定要清空所有缓存吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('缓存清空成功')
  }).catch(() => {})
}

// 查看缓存
const viewCache = (row) => {
  cacheDialog.visible = true
  cacheDialog.content = JSON.stringify(JSON.parse(row.cacheValue), null, 2)
}

// 删除缓存
const deleteCache = (cacheKey) => {
  ElMessageBox.confirm(`确定要删除缓存"${cacheKey}"吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    cacheList.value = cacheList.value.filter(item => item.cacheKey !== cacheKey)
    ElMessage.success('删除成功')
  }).catch(() => {})
}

onMounted(() => {
  // 获取系统参数列表
  getConfigList()
  
  // 获取缓存列表
  getCacheList()
})
</script>

<style scoped>
.system-config-container {
  padding: 20px;
}

.system-config-header {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.config-summary {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
}

.summary-item {
  display: flex;
  align-items: center;
}

.summary-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: rgba(62, 120, 178, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.summary-icon i {
  font-size: 28px;
  color: #3E78B2;
}

.summary-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.summary-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.config-tabs {
  margin-bottom: 20px;
}

.config-card {
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.cache-box {
  background-color: #f8f8f8;
  border-radius: 4px;
  padding: 20px;
  text-align: center;
  margin-bottom: 20px;
}

.cache-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.cache-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.cache-content-box {
  max-height: 500px;
  overflow: auto;
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 10px;
}

.cache-content-box pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: Consolas, Monaco, 'Andale Mono', monospace;
  font-size: 12px;
  line-height: 1.5;
}
</style> 